package com.tencent.api.utils;

import com.tencent.api.transaction.BankDao;
import org.junit.Test;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PSCURDPart extends BaseDao{
    @Test
    public void testInsert() throws ClassNotFoundException, SQLException {

        String sql ="INSERT INTO t_user(account, PASSWORD, nickname) values (?,?,?);";
        int rows = executeUpdate(sql, "test", "testpsword", "不知道对不对");

        if(rows>0){
            System.out.println("数据插入成功！");
        }else {
            System.out.println("数据插入失败！");
        }
    }
    @Test
    public void testUpdate() throws ClassNotFoundException, SQLException {
        //update t_user set nickname='三狗子' where id = 3;
        //编写SQL语句，动态值的部分使用？代替
        String sql ="update t_user set nickname=? where account = ?";

        int rows = executeUpdate(sql,"wxj1234","test");
        //解析结果
        if (rows>0){
            System.out.println("更新成功！");
        }else {
            System.out.println("更新失败！");
        }

    }
    @Test
    public void testDelete() throws ClassNotFoundException, SQLException {
        String sql = "delete from t_user where account=?;";
        int rows = executeUpdate(sql,"test");
        if (rows>0)
            System.out.println("删除成功！");
        else
            System.out.println("删除失败！");
    }


    /**
     * 目标：查询所用用户数据，并且封装到一个Lis<Map> list集合中
     *
     * 数据库 -> resultSet -> java -> 一行 - map(key=列名，value=列的内容) ->  Lis<Map> list
     *
     * 实现思路：
     *      遍历行数据，一行对应一个map，获取一行的列名和对应的列的属性，装配即可
     *      将map装到一个集合就可以了
     *
     * 难点：
     *      如何获取列的名称？
     *
     * @throws ClassNotFoundException
     * @throws SQLException
     */

    //自己复现一遍
    @Test
    public void testSelectOK() throws ClassNotFoundException, SQLException {
        //这里暂时用不了查询方法，因为整个体系结构中没有设置实体类


        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection connection = DriverManager.getConnection("jdbc:mysql:///atguigu", "root", "1234");
        String sql = "select * from t_user;";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        ResultSet resultSet = preparedStatement.executeQuery();
        List<Map> list = new ArrayList<>();
        ResultSetMetaData metaData = resultSet.getMetaData();
        int columnCount = metaData.getColumnCount();
        while (resultSet.next()){
            Map map = new HashMap();
            for (int i = 1; i <= columnCount; i++) {
                Object object = resultSet.getObject(i);
                String columnLabel = metaData.getColumnLabel(i);
                map.put(columnLabel,object);

            }
            list.add(map);
        }
        System.out.println(list);
        resultSet.close();
        preparedStatement.close();
        connection.close();
    }
}
